<?php
namespace m\controllers;

use Yii;
use yii\db\Query;
use common\models\Category;
use common\models\Product;
use common\models\ProductCategory;
use common\models\ProductGallery;
use common\models\Post;
use common\models\Brand;
use common\models\Banner;
use common\models\Order;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use common\components\Myhelpers;
/**
 * Index controller
 */
class ProductController extends MController
{

    public $enableCsrfValidation = false;
    /**
    * Displays homepage.
    *
    * @return mixed
    */
    //商品详情页面
    public function actionView()
    {
      $id = (int)Yii::$app->request->get('id');
      $product = product::find()
              ->select('img_url,name,product_price,des,price_unit,brand_id,spec')
              ->where(['id'=>$id,'is_show'=>1])
              ->One();
      if(!$product){
          throw new BadRequestHttpException('您所链接的商品不存在');
      }
      $brand=Brand::find()->select('name,id')->where(['id'=>$product->brand_id])->One();
      $product_img = ProductGallery::find()
            ->select('img_url,title,desc')
            ->where(['product_id'=>$id,'is_show'=>1])
            ->orderBy('id desc')
            ->all();

      //成交数量和成交记录
      $order = (new Query())
          ->select('sum(b.product_num)')
          ->from('order_product AS a')
          ->where(['a.product_id'=>$id,'b.order_status'=>4,'b.pay_status'=>2,'b.shipping_status'=>3])
          ->leftJoin('order AS b','b.id = a.order_id')
          ->leftJoin('user AS c','c.id = b.user_id')
          ->scalar();

      //var_dump($order);exit;

      //修改页面标题
      Yii::$app->view->params['page']['page_title'] = $product->name.' - ' . $this->w_config['website_name'];
      return $this->render('view',[
          'product' => $product,
          'product_img' => $product_img,
          'brand' => $brand,
          'order' => $order,
      ]);
    }

    //商品列表页

    public function actionIndex(){
      //修改页面标题
      Yii::$app->view->params['page']['page_title'] = '商品列表 - ' . $this->w_config['website_name'];

      //筛选默认条件
      $seach_res = '';
      $where = "a.is_show=1";

      $lv2name = Myhelpers::RemoveXSS(Yii::$app->request->post('lv2name'));

      if($lv2name){
          $lv2id = Category::find()->select('id')->where(['is_show'=>1,'level'=>2,'name'=>$lv2name])->scalar();
          return $lv2id;
      }
      $cate_id = (int)Yii::$app->request->get('lv2');
      if($cate_id){
          $seach_res = Category::findOne($cate_id)->name;
          $where .= " AND b.category_id = ".$cate_id;
      }
      $lv1 = (int)Yii::$app->request->get('lv1');
      if(!$cate_id && $lv1){
          $seach_res = Category::findOne($lv1)->name;
          $where .= " AND b.category_id = ".$lv1;
      }
      
      $pro_name = Myhelpers::RemoveXSS(Yii::$app->request->get('name'));
      $params = [];
      if($pro_name){
          $where .= " AND (a.name like :pro_name OR c.name like :pro_name OR a.title like :pro_name OR a.keywords like :pro_name)";
        $params = [':pro_name' => '%'.$pro_name.'%'];
      }

      //商品列表
      $query = (new Query)
          ->from('product AS a')
          ->select('a.id,a.name,a.title,a.price_unit,a.product_price,a.spec,a.img_url,d.name bname')
          ->where($where,$params)
          ->leftJoin('product_category AS b','b.product_id = a.id')
          ->leftJoin('category AS c','c.id = b.category_id')
          ->leftJoin('brand AS d','d.id = a.brand_id')
          ->distinct();
      
      $default = 10;
      $pro_list = $query->limit($default)->orderBy('a.sort_numer')->all();
      $pro_list = $this->sel_order($pro_list);

      //分页形式动态加载
      $load = Yii::$app->request->get('offset');

      if($load){
          $per = 5; //每次加载的数量
          $pro_list = $query->limit($per)->offset(($load+1)*$per)->orderBy('a.sort_numer')->all();
          $pro_list = $this->sel_order($pro_list);

          return json_encode($pro_list);
      }

      //根据传过来的一级分类名字查询对应下级分类
      $lv1name = Myhelpers::RemoveXSS(Yii::$app->request->post('lv1name'));
      if($lv1name){
          $lv1_id = Category::find()->select('id')->where(['is_show'=>1,'level'=>1,'name'=>$lv1name])->scalar();
          $cate_2 = Category::find()
              ->select('name')
              ->where(['is_show'=>1,'level'=>2,'parent_id'=>$lv1_id])
              ->orderBy('sort_number')
              ->asArray()
              ->all();
          $list_2 = [];
          foreach ($cate_2 as $key => $value) {
            array_push($list_2, $value['name']);
          }
          return json_encode($list_2);
      }

      //以json格式把数据一级分类数据分配过去
      $cate_1 = Category::find()
              ->select('name')
              ->where(['is_show'=>1,'level'=>1,'parent_id'=>0])
              ->orderBy('sort_number')
              ->asArray()
              ->all();
      $list_1 = [];
      foreach ($cate_1 as $key => $value) {
        array_push($list_1, $value['name']);
      }
      
      //写jswindow.location.href实现搜索功能

      return $this->render('index',[
          'pro_list' => $pro_list,
          'list_1' => json_encode($list_1),
          'seach_res' => $seach_res,
      ]);
    }
       
    function sel_order($pro_list){
      foreach ($pro_list as $k => $v) {
        //已售
        $pro_list[$k]['sale_sum'] = (new Query())
              ->select('sum(b.product_num)')
              ->from('order_product AS a')
              ->where(['a.product_id'=>$v['id'],'b.order_status'=>4,'b.pay_status'=>2,'b.shipping_status'=>3])
              ->leftJoin('order AS b','b.id = a.order_id')
              ->scalar();
      }
      return $pro_list;
    }
}

